文章未來將更新於:
https://kevinyay945.com/golang-project-design/2023/golang-testify/
這次我們要使用的測試工具是testify
https://github.com/stretchr/testify
他除了是一套好用的斷言lib之外(可以幫我們用白話文的方式驗證資料對不對)
他也有提供整理Test程式碼的一套流程出來,這次我主要會使用他提供的Suite這個測試的流程
https://github.com/stretchr/testify#suite-package
他的起手式大致如下
// Basic imports
import (
"testing"
"github.com/stretchr/testify/suite"
)
// In order for 'go test' to run this suite, we need to create
// a normal test function and pass our suite to suite.Run
func TestExampleTestSuite(t *testing.T) {
suite.Run(t, new(ExampleTestSuite))
}
// Define the suite, and absorb the built-in basic suite
// functionality from testify - including assertion methods.
type ExampleTestSuite struct {
suite.Suite
VariableThatShouldStartAtFive int
}
// Make sure that VariableThatShouldStartAtFive is set to five
// before each test
func (suite *ExampleTestSuite) SetupTest() {
suite.VariableThatShouldStartAtFive = 5
}
// All methods that begin with "Test" are run as tests within a
// suite.
func (suite *ExampleTestSuite) TestExample() {
suite.Equal(suite.VariableThatShouldStartAtFive, 5)
}
而會選擇用Suite這個方式來進行測試,有幾個原因
以下是我將前兩篇的工具應用完的結果
https://github.com/kevinyay945/2023_asset_management/blob/1c1b1a364199ef869423f1ab33882159031a29d9/interface/rest_api/echo_test.go